import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {FormBuilder, FormGroup, Validators, AbstractControl} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';

import {LoginService} from './login.service';
import {Global} from '../../shared/global';
import {PermissionService} from '../../service/permission.service';
import { CommonService } from 'src/app/services-common/common.service';
import { NzNotificationService } from 'ng-zorro-antd/notification';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  isVerifCode = false;
  isSpinning = false;
  loginError = false;
  passwordVisible = false;
  errorMessage = '';
  validateForm: FormGroup;

  deadlineTime: number = 0;

  constructor(
    private loginService: LoginService,
    private message: NzMessageService,
    private router: Router,
    private fb: FormBuilder,
    private permissionService: PermissionService,
    private commonService: CommonService,
    private notification: NzNotificationService
  ) {
    this.validateForm = this.fb.group({
      accountNumber: ['', [Validators.required]], // 用户名
      passWord: ['', [Validators.required]], // 密码
      codetemp: [''], // 验证码
      system: [null], // 系统
      browser: [null] // 浏览器
    });
  }

  ngOnInit(): void {}

  selectedChange() {
    if (!this.isVerifCode) {
      this.validateForm.get('codetemp')!.clearValidators();
      this.validateForm.get('codetemp')!.markAsPristine();
    } else {
      this.validateForm.get('codetemp')!.setValidators(Validators.required);
      this.validateForm.get('codetemp')!.markAsDirty();
    }
    this.validateForm.get('codetemp')!.updateValueAndValidity();
  }

  async submitForm() {
    if (this.isSpinning) {
      return
    }
    
    // 是否需要验证码
    this.selectedChange();

    let obj = this.getBrowserInfo();
    this.validateForm.value.system = obj.system;
    this.validateForm.value.browser = obj.browser;

    if (this.validateForm.valid) {
      this.isSpinning = true;
      this.loginError = false;

      let res: any = null;
      if (!this.isVerifCode) {
        // 用户名登录
        res = await this.loginService.login({...this.validateForm.value});
      } else {
        // 验证码登录
        res = await this.loginService.codeLogin({...this.validateForm.value});
      }

      if (res.code == 0) {
        if (res?.data?.isChange && res?.data?.isChange == 1) {
          // isChange：1 需要输入验证码
          this.isVerifCode = true;
          this.isSpinning = false;
          return
        }

        this.permissionService.initUserPermission();
        Global.UP = res.data;
        localStorage.setItem('userInfos', JSON.stringify(res.data));
        localStorage.setItem('ppypToken', JSON.stringify(res.data.token));
        this.menuList();
      } else {
        this.loginError = true;
        this.isSpinning = false;
        this.errorMessage = res.message || '';
      }
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  // 获取验证码
  async getMobileCode() {
    let params = {
      accountNumber: this.validateForm.value.accountNumber
    }
    const res: any = await this.loginService.getMobileCode(params);
    if (res.code == 0) {
      this.countDownTime();
      this.message.success('验证码已发送');
    } else {
      this.message.error(res.message);
    }
  }

  // 验证码倒计时
  countDownTime() {
    this.deadlineTime = 60;
    let timer = setInterval(() => {
      this.deadlineTime --;

      if (this.deadlineTime == 0) {
        clearInterval(timer);
      }
    }, 1000)
  }

  // 查询菜单列表
  menuList() {
    const messageid = this.message.loading('loading..', { nzDuration: 0 }).messageId;
    this.loginService.menuList().subscribe((res: any) => {
      this.isSpinning = false;
      this.message.remove(messageid);

      if (res.code !== 0) {
        this.message.error('菜单初始化失败');
        return
      }
      if (!res.data.sys.length) {
        this.message.error('该用户没有任何权限');
        return
      }

      if (res.code == 0) {
        // this.message.success('登录成功');
        Global.menuList = res.data || {};
        Global.activeMenu = res.data.sys[0].id;
        localStorage.setItem('activeMenu', res.data.sys[0].id);
        localStorage.setItem('isLogin', 'true');
        this.notification.success('登录成功', '欢迎使用爱思商城后台管理系统');

        let menuData = res.data.sys[0].menu || [];
        this.router.navigate([menuData[0].children[0].path], { replaceUrl: true });
      } else {
        this.message.error(res.message);
      }
    }, err => {
      this.isSpinning = false;
      this.message.remove(messageid);
      this.message.error(err);
    });
  }

  /**
   * 获取浏览器名字
   * @returns
   */
  getBrowserInfo() {
    let obj = {
      // 系统
      system: 'Unknown',
      // 浏览器
      browser: 'Unknown',
    };
    let userAgent: any = navigator.userAgent.toLowerCase();
    let regStr_ie = /msie [\d.]+;/gi;
    let regStr_ff = /firefox\/[\d.]+/gi;
    let regStr_chrome = /chrome\/[\d.]+/gi;
    let regStr_saf = /safari\/[\d.]+/gi;

    try {
      //IE
      if (userAgent.indexOf('msie') > 0) {
        obj.browser = userAgent.match(regStr_ie)[0];
      }
      //firefox
      if (userAgent.indexOf('firefox') > 0) {
        obj.browser = userAgent.match(regStr_ff)[0];
      }
      //Chrome
      if (userAgent.indexOf('chrome') > 0) {
        obj.browser = userAgent.match(regStr_chrome)[0];
      }
      //Safari
      if (userAgent.indexOf('safari') > 0 && userAgent.indexOf('chrome') < 0) {
        obj.browser = userAgent.match(regStr_saf)[0];
      }

      if (userAgent.indexOf('win') > -1) {
        obj.system = 'Windows';
        if (userAgent.indexOf('windows nt 5.0') > -1) {
          obj.system = 'Windows 2000';
        } else if (userAgent.indexOf('windows nt 5.1') > -1 || userAgent.indexOf('windows nt 5.2') > -1) {
          obj.system = 'Windows XP';
        } else if (userAgent.indexOf('windows nt 6.0') > -1) {
          obj.system = 'Windows Vista';
        } else if (userAgent.indexOf('windows nt 6.1') > -1 || userAgent.indexOf('windows 7') > -1) {
          obj.system = 'Windows 7';
        } else if (userAgent.indexOf('windows nt 6.2') > -1 || userAgent.indexOf('windows 8') > -1) {
          obj.system = 'Windows 8';
        } else if (userAgent.indexOf('windows nt 6.3') > -1) {
          obj.system = 'Windows 8.1';
        } else if (userAgent.indexOf('windows nt 6.2') > -1 || userAgent.indexOf('windows nt 10.0') > -1) {
          obj.system = 'Windows 10';
        } else {
          obj.system = 'Unknown';
        }
      } else if (userAgent.indexOf('iphone') > -1) {
        obj.system = 'Iphone';
      } else if (userAgent.indexOf('mac') > -1) {
        obj.system = 'Mac';
      } else if (userAgent.indexOf('x11') > -1 || userAgent.indexOf('unix') > -1 || userAgent.indexOf('sunname') > -1 || userAgent.indexOf('bsd') > -1) {
        obj.system = 'Unix';
      } else if (userAgent.indexOf('linux') > -1) {
        if (userAgent.indexOf('android') > -1) {
          obj.system = 'Android';
        } else {
          obj.system = 'Linux';
        }
      } else {
        obj.system = 'Unknown';
      }
    } catch (error) {

    }
    return obj;
  }
}
